package forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import java.sql.*;
import java.util.Vector;

public class RegisterForm extends ActionForm {

	private static final long serialVersionUID = 2L;
	
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		
	}
	
	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		
		ActionErrors errors = new ActionErrors();
		
		String userNameParam = request.getParameter("username");
		String passwordParam = request.getParameter("password");
		String passwordVerifyParam = request.getParameter("passwordVerify");
		String emailParam = request.getParameter("email");
		
	

		try{
			Class.forName("org.postgresql.Driver");
			Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost/135DB?user=postgres&password=admin");
		
			if(userNameParam != null)
			{
				
				PreparedStatement stmt;
				ResultSet rset;
				stmt = connect.prepareStatement("SELECT * FROM users");
				rset = stmt.executeQuery();
				Vector<String> dbuserID = new Vector<String>();
				Vector<String> dbusernames = new Vector<String>();
				Vector<String> dbemails = new Vector<String>();
				while (rset.next())
				{
					dbuserID.add(rset.getString("user_id"));
					dbusernames.add(rset.getString("user_name"));
					dbemails.add(rset.getString("email"));
				}
			
				if(dbusernames.contains(userNameParam))
				{
					errors.add("user", new ActionMessage("errors.usernameDup"));
					
				}
				if(!passwordParam.equals(passwordVerifyParam))
				{
					errors.add("password", new ActionMessage("errors.passwords"));
					
				}
				if(dbemails.contains(emailParam))
				{
					errors.add("email", new ActionMessage("errors.emailDup"));
					
				}
			}
		}catch (Exception e) {
				
				e.printStackTrace();
				return null;
			}
		
		return errors;
	}
}
